package com.fstec.ks.master.impl;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import com.sinotn.ks.definition.RequestMessage;
import com.sinotn.ks.netty.handler.ExamHandler;

public class MessageHandler extends ExamHandler{

	public MessageHandler(){}

	@Override
	public void messageRead(ChannelHandlerContext ctx, RequestMessage msg) throws Exception {
		Channel channel=ctx.channel();
		NettyClient client=channel.attr(NettyClient.NETTY_CLIENT).get();
		if(client!=null){
			client.onRcv(msg);
		}
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Channel channel=ctx.channel();
		NettyClient client=channel.attr(NettyClient.NETTY_CLIENT).get();
		if(client!=null){
			client.onInactive();
		}
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if(evt instanceof IdleStateEvent){
			IdleStateEvent idleEvent = (IdleStateEvent) evt;
			IdleState idleState= idleEvent.state();
			/*
			if (idleState == IdleState.READER_IDLE) {// 读超时
				Channel channel=ctx.channel();
				NettyClient client=channel.attr(NettyClient.NETTY_CLIENT).get();
				if (client!=null){
					client.onRspTimeout();
				}
			} else 
			*/
			if (idleState == IdleState.WRITER_IDLE) {// 写空闲超时，发送心跳信息
				ctx.channel().writeAndFlush(Boolean.TRUE);
			}
		}else{
			super.userEventTriggered(ctx, evt);
		}
	}
}
